package com.aube.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aube.R;
import com.aube.guide.Target;
import com.aube.model.VideoHighlightItem;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by huyaonan on 16/7/21.
 */
public class HighlightVideoView extends RelativeLayout {

    private Context mContext;
    private Target targetView;

    private List<View> mSmallTipViews;
    private List<View> mBigTipViews;
    private HashMap<String, Float> mViewPosMaps;

    private static final String TAG_SMALL = "TAG_SMALL_";
    private static final String TAG_BIG = "TAG_BIG_";

    private static final int RANGE = 5;

    private int mLastProgress = 0;

    private boolean mToRight = true;

    private long mVideoLength = 0;
    private List<VideoHighlightItem> mHightlightsMap;

    public HighlightVideoView(Context context) {
        this(context, null);
    }

    public HighlightVideoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HighlightVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if(targetView == null)
            return;

        Rect rect = targetView.getRect();
        int y = rect.top;// + (rect.bottom - rect.top)/4;

        if(mSmallTipViews != null) {
            for(View view : mSmallTipViews) {
                String tag = (String) view.getTag();
                String time = tag.substring(TAG_SMALL.length());

                float position = getPosition(time);
                if(position < 0)
                    continue;

                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight();

                int x = (int) (rect.left + (rect.right-rect.left)*position/100);

                view.layout(x-width/2, y-height, x+width/2, y);
            }
        }

        if(mBigTipViews != null) {
            for(View view : mBigTipViews) {
                String tag = (String) view.getTag();
                String time = tag.substring(TAG_BIG.length());

                float position = getPosition(time);
                if(position < 0)
                    continue;

                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight();

                int x = (int) (rect.left + (rect.right-rect.left)*position/100);

                view.layout(x-width/2, y-height, x+width/2, y);
            }
        }
    }

    private float getPosition(String key) {
        if(mViewPosMaps != null && mViewPosMaps.containsKey(key))
            return mViewPosMaps.get(key);
        return -1f;
    }

    public void startUpdateProgress(int progress) {
        if(mViewPosMaps != null) {
            List<String> mActiveList = new ArrayList<>();
            Iterator<Map.Entry<String, Float>> iterator = mViewPosMaps.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Float> entry = iterator.next();

                View small = findViewWithTag(TAG_SMALL + entry.getKey());

                if(entry.getValue() - RANGE <= progress && progress <= entry.getValue() + RANGE) {
                    if(small != null)
                        small.setAlpha(0f);
                    float alpha = (RANGE - Math.abs(progress - entry.getValue()))*1f/RANGE;
                    findViewWithTag(TAG_BIG + entry.getKey()).setAlpha(alpha);

                    mActiveList.add(entry.getKey());
                } else {
                    if(small != null)
                        small.setAlpha(1f);
                    findViewWithTag(TAG_BIG + entry.getKey()).setAlpha(0f);
                }
            }

            //只显示一个
            if(mActiveList.size() >= 2) {
                if(progress > mLastProgress)
                    mToRight = true;
                else if(progress < mLastProgress)
                    mToRight = false;
                float targetProgress=0;
                String targetTime = null;
                for(String s : mActiveList) {
                    float p = mViewPosMaps.get(s);

                    if(targetProgress == 0) {
                        targetProgress = p;
                        targetTime = s;
                        continue;
                    }

                    if(targetProgress < progress && p < progress) {
                        if(p > targetProgress) {
                            targetProgress = p;
                            targetTime = s;
                        }
                    } else if(targetProgress > progress && p > progress) {
                        if(p < targetProgress) {
                            targetProgress = p;
                            targetTime = s;
                        }
                    } else {
                        if(mToRight) {
                            if(p > targetProgress) {
                                targetProgress = p;
                                targetTime = s;
                            }
                        } else {
                            if(p < targetProgress) {
                                targetProgress = p;
                                targetTime = s;
                            }
                        }
                    }
                }

                if(StringUtils.isNotBlank(targetTime)) {
                    for(String s : mActiveList) {
                        if(!s.equalsIgnoreCase(targetTime)) {
                            View small = findViewWithTag(TAG_SMALL + s);
                            if(small != null)
                                small.setAlpha(1f);
                            findViewWithTag(TAG_BIG + s).setAlpha(0f);
                        }
                    }
                }
            }
        }

        mLastProgress = progress;
    }

    public void onStartTrackingTouch(long progress) {
        mLastProgress = (int) progress;
        mToRight = true;
    }

    public void endUpdateProgress() {
        if(mBigTipViews != null) {
            for (View view : mBigTipViews)
                view.setAlpha(0f);
        }

        if(mSmallTipViews != null) {
            for(View view : mSmallTipViews)
                view.setAlpha(1f);
        }
    }

    public void setupViews(Target target, List<VideoHighlightItem> items, int duration) {
        if(items == null || target == null)
            return;
        this.targetView = target;

        int imgWidth = 400;
        int imgHeight = imgWidth * 9 / 16;

        mVideoLength = duration;
        mHightlightsMap = items;

        mSmallTipViews = new ArrayList<>();
        mBigTipViews = new ArrayList<>();
        mViewPosMaps = new HashMap<>();
        for(VideoHighlightItem item : items) {
            if(StringUtils.isNotBlank(item.bubbleKey)) {
                View small = LayoutInflater.from(mContext).inflate(R.layout.item_video_tip_small, null);
                mSmallTipViews.add(small);
                addView(small);
                small.setTag(TAG_SMALL + item.time);

                final ImageView mTipSmall = (ImageView) small.findViewById(R.id.video_tip_small);
                if(item.getImgDrawableId() != 0)
                    mTipSmall.setImageDrawable(mContext.getResources().getDrawable(item.getImgDrawableId()));
                //防止图片链接无效
//                ImageLoader.getInstance(mContext).preloadBitmap(item.bubbleurl, new ImageLoader.IPreloadCallback<Bitmap>() {
//                    @Override
//                    public void onSuccess(Bitmap bitmap) {
//                        if(bitmap != null)
//                            mTipSmall.setImageBitmap(bitmap);
//                    }
//
//                    @Override
//                    public void onFail() {
//
//                    }
//                });
            }

            View big = LayoutInflater.from(mContext).inflate(R.layout.item_video_tip_big, null);
            LayoutParams params = new LayoutParams(imgWidth + 2 * Utils.dip2px(mContext, 5), ViewGroup.LayoutParams.WRAP_CONTENT);
            mBigTipViews.add(big);
            addView(big, params);
            big.setTag(TAG_BIG + item.time);

            ImageView mTipBig = (ImageView) big.findViewById(R.id.video_tip_big);
            ImageLoader.getInstance(mContext).fillImage(mTipBig, item.picurl, 400, 400);
            TextView mTipDes = (TextView) big.findViewById(R.id.video_tip_des);
            mTipDes.setText(item.title);

            //resize img
            LinearLayout.LayoutParams imgParams = (LinearLayout.LayoutParams) mTipBig.getLayoutParams();
            imgParams.width = imgWidth;
            imgParams.height = imgHeight;

            if(duration > 0) {
                float progress = Integer.parseInt(item.time) * 100f / duration;
                mViewPosMaps.put(item.time, progress);
            }

            big.setAlpha(0f);
        }

        for(View view : mBigTipViews)
            view.bringToFront();

        requestLayout();
    }

    public void setVideoLength(long length) {
        if(length <= 0)
            return;

        this.mVideoLength = length;
        if(mViewPosMaps != null && mViewPosMaps.size() > 0)
            return;
        if(mHightlightsMap != null && mHightlightsMap.size() > 0) {
            mViewPosMaps = new HashMap<>();

            for(VideoHighlightItem item : mHightlightsMap) {
                if(mVideoLength > 0) {
                    float progress = Integer.parseInt(item.time) * 100f / mVideoLength;
                    mViewPosMaps.put(item.time, progress);
                }
            }

            requestLayout();
        }
    }

}
